import es
import playerlib
import time
import sys
import os
import gamethread
from langlib import Strings
from configobj import ConfigObj

'''
== Team DeathMatch ==
  By Errant

- 23012008a -

'''

#plugin information
info = es.AddonInfo() 
info.name     = 'Team DeathMatch' 
info.version  = '23012008a' 
info.url      = 'http://mattie.info/cs' 
info.basename = 'tdm' 
info.author   = 'Errant'

'''
 ** Configuration and globals
'''
# Constants
PATH =  es.getAddonPath("tdm")
CFGPATH = PATH + "/cfg/"
MSG_PREFIX = "#green[TDM] #lightgreen"

# override the problems
# versioning, public console variable
version = es.ServerVar("tdm_version", info.version, "Team DeathMatch Version")
version.makepublic()

# langlib object
text = Strings(PATH + "/languages.ini")

# cfg object
cfg = ConfigObj(CFGPATH + "tdm.ini")

# some more vars
est_loaded = es.ServerVar("est_version")
playersdb = {}
team2 = None
team3 = None


'''
 ** Internal classes
'''

class tdmLogging(object):
    '''
    Basic logging class
    '''
    file = None
    datefrmt = '%a, %d %b %Y %H:%M:%S'
    DEBUG=3
    INFO=2
    WARNING=1
    ERROR=0
    def __init__(self, level=DEBUG, file=None, datefrmt=None):
        '''
        Sets up the class - most important is the level
        '''
        if datefrmt:
            self.datefrmt = datefrmt
        self.level = level
        if file:
            self.file = es.getAddonPath("tdm") + "/logs/" + file
        else:
            # logging into a date formatted file
            self.file = es.getAddonPath("tdm") + "/logs/" + time.strftime('%d_%b_%Y') + ".log"
    def _log(self, message, level):
        '''
        Logs a message to the file with a timestamp
        - Not wonderful atm as there is no error catching if the file pointer errors (or if the dir doesnt exist)
        '''
        es.dbgmsg(int(level), message)
        if not os.path.exists(self.file):
            # create the log fiel if it doesnt exist
            fp = open(self.file,"wb")
            fp.write("# ===============================================\r")
            fp.write(" TDM Log File [" + time.strftime(self.datefrmt) + "]\r")
            fp.write("# ===============================================\r")
            fp.write("# ===============================================\r")
        else:
            fp = open(self.file,"a")
        fp.write("%s %s \r" % (time.strftime(self.datefrmt), message))
        fp.close()
    def debug(self, message):
        '''
        Logs a debug level message
         - Just a handy interface to  self._log()
        '''
        if self.level >= self.DEBUG:
            self._log("[TDM] DEBUG:   " + message, 3)
        
    def error(self, message):
        '''
        Logs an error level message
         - Just a handy interface to  self._log()
        '''
        if self.level >= self.ERROR:
            self._log("[TDM] ERROR:    " + message, 0)
    def warning(self, message):
        '''
        Logs a warning level message
         - Just a handy interface to self._log()
        '''
        if self.level >= self.WARNING:
            self._log("[TDM] WARNING: " + message, 1)
    def info(self, message):
        '''
        Logs an info level message
         - Just a handy interface to self._log()
        '''
        if self.level >= self.INFO:
            self._log("[TDM] INFO:   " + message, 2)
    def setLoggingLevel(self, newlevel):
        self.level = newlevel 

class tdmError(Exception):
    '''
    Basic overall error class
    '''
    def __init__(self, message):
        self.message =  "(" + self.__class__.__name__ + ") " + message
        logging.error(self.message)
    def __str__(self):
        return self.message        
        
# further error classes
class tdmUserError(tdmError):
    pass
# end error classes

class tdmPlayer(playerlib.Player):
    '''
    Extends playerlib to provide special/extra functions
    '''
    lastSpawnTime = None
    def spawn(self):
        '''
        spawn the player
        '''
        if (cfg["tdm_respawn_method"] == "est" or os.environ['OS'].startswith("windows")) and est_loaded:
            es.server.command("est_spawn %s" % self.id)
        elif cfg["tdm_respawn_method"] == "es":
            es_respawn.respawn(self.id)
        else:
            raise tdmUserError, 'Unable to respawn player %s' % self.id 
    def getSpawnInterval(self):
        '''
        Grabs the interval since the player last spawned
        '''
        if self.lastSpawnTime:
            return (time.time() - self.lastSpawnTime)
    def setSpawnTime(self):
        self.lastSpawnTime = time.time()
        
    def tell(self, string_name):
        '''
        Tell the player something
        '''
        es.tell(self.id, "#multi", MSG_PREFIX + text(string_name,None,self.get("lang"))
        
class tdmTeamTracker(object):
    '''
    Tracks a team - the players, the score and other settings / data
    '''
    tickets = int(cfg["tdm_team_starting_tickets"])
    teamid = None
    def __init__(self, teamid):
        self.teamid = teamid
    def dec(self, amt):
        '''
        Remove some tickets
        '''
        self.tickets -= int(amt)
    def inc(self, amt):
        '''
        Add some tickets
        '''
        self.tickets += int(amt)
        
'''
 ** Internal Methods
'''
def try_load_spawn_libs():
    '''
    Tries to load the relevant spawn library
    '''
    global cfg
    if cfg["tdm_respawn_method"] == "es" or os.environ['OS'].startswith("windows"):
        try:
            global esSpawn
            import es_respawn as esSpawn
        except:
            # oops the module aint here :(
            logging.error("es_respawn cannot be loaded! Trying EST instead")
            if est_loaded:
                cfg["tdm_respawn_method"] == "est"
                logging.warning("TDM will use EST instead of es_respawn for the spawn method")
                return True
            else: 
                logging.error("TDM will use EST instead of es_respawn for the spawn method")
                return False
'''
Events and preload stuff
'''

#
# CREATE THE LOGGING INSTANCE
logging = tdmLogging(int(cfg["tdm_log_level"]))
#

#try some stuff to load the respawn scripts
if not try_load_spawn_libs():
    # shit problem! we needto "crash" here
    gamethread.delayed(5, es.unload, ("tdm"))
    raise tdmError, 'Unable to find a valid spawn method, install EST or es_respawn and retry. Addon will be unloaded in 5 seconds.'    

def load():
    '''
    Initialise the mod
     * Parse the currently connected players and process them
    '''
    global playersdb
    # parse the list of currently connected users....
    for id in es.getUseridList()
        temp = tdmPlayer(id)
        temp.tell("loading_mod")
        temp.set("freeze", 1)
        playersdb[id] = temp
    # remember players are FROZEN at this point!
    # start the team trackers
    team2 = tdmTeamTracker(2)
    team3 = tdmTeamTracker(3)
    # unfreeze and kill players
    for id in playersdb:
        playersdb[id].set("freeze", 0)
        playersdb[id].kill()
        
def player_death(event_var):
    '''
    
    '''
    if int(playersdb[event_var["userid"]].get("team")) == 2:
        team3.dec(cfg["tdm_tickets_cost_death"])
    elif int(playersdb[event_var["userid"]].get("team")) == 3:
        team2.dec(cfg["tdm_tickets_cost_death"])